﻿namespace LiteBlog.Components
{
    using System.Configuration;
    using System.Web;
    using LiteBlog.Repositories.Contracts;
    using LiteBlog.Components.Contracts;
    using System.IO;
    using Repositories.Common;

    public class ConfigComp : IConfigComp
    {
        private string dataPath = string.Empty;
        private IDataContext _dataContext;

        public ConfigComp(IDataContext dataContext)
        {
            _dataContext = dataContext;
        }

        // Date format for storing values in the Db and retrieving data from there
        public static string DateFormat
        {
            get
            {
                return ConfigurationManager.AppSettings["DateFormat"];
            }
        }

        public static string DefaultPassword
        {
            get
            {
                return ConfigurationManager.AppSettings["DefaultPassword"];
            }
        }

        public string DataPath
        {
            get
            {
                return _dataContext.DataPath;
            }
            set
            {
                _dataContext.DataPath = value;
            }
        }

        public static string AppPath
        {
            get
            {
                return HttpContext.Current.Server.MapPath("~");
            }
        }

        public static string AppUrl
        {
            get
            {
                string appUrl = "{0}://{1}{2}";
                var request = HttpContext.Current.Request;
                var requestUrl = request.Url;
                // Scheme: http, Authority: vijayt.com[:80], ApplicationPath: /appName
                var appPath = request.ApplicationPath;
                if (request.ApplicationPath.Equals(@"/"))
                    appPath = string.Empty;
                return string.Format(appUrl, requestUrl.Scheme, requestUrl.Authority, appPath);
            }
        }

        public string DocumentVirtualPath
        {
            get
            {
                return VirtualPathUtility.ToAbsolute("~/Docs");
            }
        }

        public string DocumentPath
        {
            get
            {
                var rootPath = HttpContext.Current.Server.MapPath("~");
                var docPath = Path.Combine(rootPath, "Docs");
                if (!Directory.Exists(docPath))
                        Directory.CreateDirectory(docPath);
                return docPath;
            }
        }

        public string BackupPath
        {
            get
            {
                var rootPath = HttpContext.Current.Server.MapPath("~");
                var backupPath = Path.Combine(rootPath, "Backups");
                if (!Directory.Exists(backupPath))
                    Directory.CreateDirectory(backupPath);
                return backupPath;
            }
        }
    }
}